from supergirl.models import Student
from gideon.service.starlabs import GideonHandler
from supergirl.views.privatebasehandler import PrivateBaseHandler
from supergirl.forms.paymentrecordforms import PaymentRecordModelForm, PaymentRecordAndStudentModelForm
from oracle.base.tools import get_random_string


class PaymentRecordHandler(PrivateBaseHandler):
    display_list = ["customer", "consultant", "pay_type", "paid_fee", "class_list", "apply_date", "confirm_status",
                    "confirm_date", "confirm_user", "note", ]
    display_operation_button = []

    def get_model_form_class(self, handler_type=None, *args, **kwargs):
        customer_key = kwargs.get("customer_key", "")
        if Student.objects.filter(customer__key=customer_key).exists():
            return PaymentRecordModelForm
        else:
            return PaymentRecordAndStudentModelForm

    def get_urls(self):
        patterns = super().get_urls()
        # 涉及金钱，删除和修改的操作不允许出现
        return patterns[0:2]

    def form_handler(self, form, is_update=False, *args, **kwargs):
        customer_key = kwargs.get("customer_key", "")
        student_obj = Student.objects.filter(customer__key=customer_key)
        if student_obj.exists():
            student_obj = student_obj.first()
        else:
            qq = form.cleaned_data.get("qq")
            mobile = form.cleaned_data.get("mobile")
            emergency_contract = form.cleaned_data.get("emergency_contract")
            # TODO 性能问题
            # 确保获取的key唯一
            while True:
                key = get_random_string(24)
                if not self.model_class.objects.filter(key=key).exists():
                    break
            student_obj = Student.objects.create(key=key, qq=qq, mobile=mobile, emergency_contract=emergency_contract,
                                                 customer_id=customer_key)
        class_list = form.cleaned_data.get("class_list")
        if class_list:
            student_obj.class_list.add(class_list.id)
        return super().form_handler(form, is_update, *args, **kwargs)

    def show_confirm_date_field(self, obj=None, is_title=False, *args, **kwargs):
        time_format = '%Y-%m-%d %H:%M:%S'
        return self.format_datetime_field(obj, "confirm_date", is_title=is_title, time_format=time_format)

    def show_apply_date_field(self, obj=None, is_title=False, *args, **kwargs):
        time_format = '%Y-%m-%d %H:%M:%S'
        return self.format_datetime_field(obj, "apply_date", is_title=is_title, time_format=time_format)


class CheckPaymentRecordHandler(GideonHandler):
    """
    确认审批时处理方法
    """
    action_list = ["confirm", "cancel", ]
    display_list = ["checkbox", "customer", "consultant", "pay_type", "paid_fee", "class_list", "apply_date",
                    "confirm_status", "note", ]
    display_operation_button = []
    display_manager_button = []
    order_list = ["confirm_status", "-id"]

    def action_multi_confirm(self, title=False, data=None, url=None, *args, **kwargs):
        if data is None:
            data = dict()
        if title:
            return '批量确认'
        else:
            key_list = self.request.POST.getlist('key')
            for key in key_list:
                payment_object = self.model_class.objects.filter(key=key, confirm_status=1).first()
                if not payment_object:
                    continue
                payment_object.confirm_status = 2
                payment_object.save()
                payment_object.customer.class_status = 1
                payment_object.customer.save()
                payment_object.customer.student.student_status = 2
                payment_object.customer.student.save()

            status = "success"
            data.update(
                {
                    "head_title": "批量确认成功",
                    "title": "批量确认交费以及报班成功",
                    "href": self.reverse_url_list(self.request, *args, **kwargs),
                    "button_text": "返回列表页"
                }
            )
        return status

    def action_multi_cancel(self, title=False, data=None, url=None, *args, **kwargs):
        if data is None:
            data = dict()
        if title:
            return '批量驳回'
        else:
            key_list = self.request.POST.getlist('key')
            self.model_class.objects.filter(key__in=key_list, confirm_status=1).update(confirm_status=3)

            status = "success"
            data.update(
                {
                    "head_title": "批量驳回成功",
                    "title": "批量驳回费用申报成功",
                    "href": self.reverse_url_list(self.request, *args, **kwargs),
                    "button_text": "返回列表页"
                }
            )
        return status

    def get_urls(self):
        patterns = super().get_urls()
        # 涉及金钱，只能进行审批，添加、删除和修改的操作不允许出现
        return patterns[0:1]

    def show_confirm_date_field(self, obj=None, is_title=False, *args, **kwargs):
        time_format = '%Y-%m-%d %H:%M:%S'
        return self.format_datetime_field(obj, "confirm_date", is_title=is_title, time_format=time_format)

    def show_apply_date_field(self, obj=None, is_title=False, *args, **kwargs):
        time_format = '%Y-%m-%d %H:%M:%S'
        return self.format_datetime_field(obj, "apply_date", is_title=is_title, time_format=time_format)
